package com.sixmac.police.intercept;

import com.sixmac.core.constant.Constant;
import com.sixmac.core.plugins.dao.Blade;
import com.sixmac.core.shiro.ShiroKit;
import com.sixmac.core.toolbox.Paras;
import com.sixmac.core.toolbox.kit.AESKit;
import com.sixmac.core.toolbox.kit.CookieKit;
import com.sixmac.module.AdminUser;
import com.sixmac.police.filter.FilterUser;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * Created by 杨春 on 2017/11/14.
 */
public class LoginIntercpetor implements HandlerInterceptor {

    Blade clientUserBlade = Blade.create(AdminUser.class);

    //请求执行方法之前执行
    @Override
    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response, Object handler) throws Exception {
        AdminUser user = (AdminUser) request.getSession().getAttribute(Constant.SESSION_ADMIN_USER);
        if (null == user) {
            Cookie qnlm_userInfo = CookieKit.getCookieObject(Constant.COOKIE_USER, request);
            if (null != qnlm_userInfo) {
                String userInfo = AESKit.decrypt(qnlm_userInfo.getValue());
                user = clientUserBlade.findFirstBy("number = #{mobile} and password = #{password} ", Paras.create().set("mobile", userInfo.split("-")[0]).set("password", ShiroKit.md5(userInfo.split("-")[1], "")));
                if(null != user){
                    //创建session
                    HttpSession session = request.getSession();
                    //屏蔽用户信息
                    FilterUser.filterUser(user);
                    //往session中储存用户信息
                    session.setAttribute(Constant.SESSION_ADMIN_USER, user);
                }
            }else{
                String url = request.getRequestURI();
                if (url.endsWith("/admin/")||url.endsWith("/admin/login")||url.endsWith("/admin/captcha")||url.endsWith("/admin/check")||url.endsWith("/admin/go")){
                    return true;
                }else{
                    response.sendRedirect(request.getContextPath() + "/admin/login");
                    return false;
                }
            }
        }
        return true;
    }

    //执行方法之后执行
    @Override
    public void postHandle(HttpServletRequest request,
                           HttpServletResponse response, Object handler,
                           ModelAndView modelAndView) throws Exception {
//        System.out.println("MyIntercpetor.postHandle()");

    }

    //最终执行的方法
    @Override
    public void afterCompletion(HttpServletRequest request,
                                HttpServletResponse response, Object handler, Exception ex)
            throws Exception {
//        System.out.println("MyIntercpetor.afterCompletion()");

    }

}
